package com.industrial.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import javax.validation.Validator;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.MD5Utils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.system.api.domain.RegisterWhiteUserForm;
import com.industrial.system.api.domain.SysDept;
import com.industrial.system.domain.*;
import com.industrial.system.domain.vo.TreeSelect;
import com.industrial.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.industrial.common.core.constant.UserConstants;
import com.industrial.common.core.exception.ServiceException;
import com.industrial.common.core.utils.SpringUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.bean.BeanValidators;
import com.industrial.common.datascope.annotation.DataScope;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.system.api.domain.SysRole;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.service.ISysConfigService;
import com.industrial.system.service.ISysUserService;

/**
 * 用户 业务层处理
 * 
 * @author ttql
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        List<SysUser> sysUserArgs = userMapper.selectUserList(user);
        if(sysUserArgs != null && !sysUserArgs.isEmpty()){
            //注：这里不要使用stream流操作，会引起前端分页失败
            for(SysUser item : sysUserArgs){
                String province = item.getProvince();
                String city = item.getCity();
                String district = item.getDistrict();
                StringBuilder areaStr = new StringBuilder();
                if(StringUtils.isNotBlank(province)){
                    areaStr.append(redisTemplate.opsForValue().get("area:" + province));
                }
                if(StringUtils.isNotBlank(city)){
                    areaStr.append("-").append(redisTemplate.opsForValue().get("area:" + city));
                }
                if(StringUtils.isNotBlank(district)){
                    areaStr.append("-").append(redisTemplate.opsForValue().get("area:" + district));
                }
                item.getExtData().put("area",areaStr.toString());
            }
        }
        return sysUserArgs;
    }


    public SysUser selectUserByDeptId(String deptId){
        if(StringUtils.isBlank(deptId)){
            throw new RuntimeException("部门ID没有找到");
        }
        return userMapper.selectUserByDeptId(deptId);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(String userId)
    {
        SysUser sysUser = userMapper.selectUserById(userId);
        String province = sysUser.getProvince();
        String city = sysUser.getCity();
        String district = sysUser.getDistrict();
        List<String> areaArgs = new ArrayList<String>();
        if(StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city) && StringUtils.isNotBlank(district)){
            areaArgs.add(province);
            areaArgs.add(city);
            areaArgs.add(district);
        }else if(StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city) && StringUtils.isBlank(district)){
            areaArgs.add(province);
            areaArgs.add(city);
        }else if(StringUtils.isNotBlank(province) && StringUtils.isBlank(city) && StringUtils.isBlank(district)){
            areaArgs.add(province);
        }
        sysUser.setAreaCodeArgs(areaArgs);
        return sysUser;
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user)
    {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
//        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        if (StringUtils.isNotNull(info) && !StringUtils.equals(info.getUserId(),userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user)
    {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
//        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        if (StringUtils.isNotNull(info) && !StringUtils.equals(info.getUserId(),userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user)
    {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
//        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        if (StringUtils.isNotNull(info) && !StringUtils.equals(info.getUserId(),userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(String userId)
    {
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();

        if (!(SysUser.isAdmin(SecurityUtils.getUserId()) || ArrayUtil.contains(roles.toArray(),"p_01_011")))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user)
    {
        List<String> areaCodeArgs = user.getAreaCodeArgs();
        if(areaCodeArgs != null && !areaCodeArgs.isEmpty()){
            int size = areaCodeArgs.size();
            if(size == 1){
                user.setProvince(areaCodeArgs.get(0));
            }else if(size == 2){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
            }else if (size == 3){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
                user.setDistrict(areaCodeArgs.get(2));
            }
        }
        user.setUserId(IdUtil.simpleUUID());
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user)
    {
        String userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        List<String> areaCodeArgs = user.getAreaCodeArgs();
        if(areaCodeArgs != null && !areaCodeArgs.isEmpty()){
            int size = areaCodeArgs.size();
            if(size == 1){
                user.setProvince(areaCodeArgs.get(0));
            }else if(size == 2){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
            }else if (size == 3){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
                user.setDistrict(areaCodeArgs.get(2));
            }
        }
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(String userId, String[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * @param sysUser
     */
    @Override
    public AjaxResult updateUserUserNameOrPassowrdByUserId(SysUser sysUser) {
        if(!checkUserNameUnique(sysUser)){
            return AjaxResult.warn("用户名已存在");
        }
        userMapper.updateUser(sysUser);
        return AjaxResult.success("修改成功");
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        user.setLastChangePwTime(DateUtils.getNowDate());
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password,DateUtils.getNowDate());
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        String[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (String postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (String roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(String userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(String[] userIds)
    {
        for (String userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * <p>
     * 查询管理员用户
     * </p>
     *
     * @return 管理员用户的集合
     */
    @Override
    public List<SysUser> selectAdminUserList() {
        SysUser sysUser = new SysUser();
        sysUser.setIsAdminUser("1");
        return userMapper.selectUserList(sysUser);
    }

    /**
     * 通过用户ID查询用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public SysUser getUserInfoByUserId(String userId) {
        return userMapper.getUserInfoByUserId(userId);
    }

    /**
     * 查询管理员用户
     *
     * @return
     */
    @Override
    public List<SysUser> getAdminUserList() {
        SysUser sysUser = new SysUser();
        sysUser.setIsAdminUser("1");
        sysUser.setDelFlag("0");
        return userMapper.selectUserList(sysUser);
    }

    /**
     * 在给定的用户Id列表中，查询到管理员用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public SysUser getAdminUserInfoByAppointUserId(String userId) {
        SysUser result = userMapper.selectAdminUserInfoByAppointUserIdArgs(userId);
        return result;
    }

    @Override
    public void clearAdminUserInfo(SysUser sysUser) {
        userMapper.clearAdminUserInfo(sysUser);
    }

    @Override
    public AjaxResult insertUserRole() {
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        List<String> collect = sysUsers.stream().filter(item -> !item.getUserId().equals("1")).map(SysUser::getUserId).collect(Collectors.toList());
        List<SysUserRole> list = new ArrayList<>();
        int count = 0,p= 0;
        for(String item : collect){
            SysUserRole sysUserRole = new SysUserRole();

            sysUserRole.setUserId(item);
            sysUserRole.setRoleId("1ae0bb3bd1c3420a814de76b2c154ab0");

            list.add(sysUserRole);
            count++;
            if(count >= 100){
                roleMapper.batchInserRole(list);
                count = 0;
                list.clear();
                log.info("执行了第{}次",p);
                p++;
            }
        }
        if(count != 0 ){
            roleMapper.batchInserRole(list);
        }
        return AjaxResult.success();
    }

    @Override
    public List<SysUser> getCurrentUserNameExist(List<String> uscc) {
        List<SysUser> result = userMapper.selectUserByUserNameArgs(uscc);
        return result;
    }

    /**
     * 批量插入用户
     *
     * @param users
     */
    @Override
    public void batchInsertUser(List<SysUser> users) {
        userMapper.batchInsertUser(users);
    }

    @Override
    public void batchUpdateUser(List<SysUser> users) {
        userMapper.batchUpdateUser(users);
    }

    /**
     *
     */
    @Override
    public List<SysUserRoleMenu> queryCurrentUserRoleAndPre(Map<String,String> params) {
        String userId = SecurityUtils.getUserId();
        String roleName = params.get("roleName");
        List<SysUserRoleMenu> sysUserRoleMenu = userMapper.queryCurrentUserRoleAndPre(userId,roleName);
        return sysUserRoleMenu;
    }

    /**
     *
     */
    @Override
    public List<TreeSelect> queryUserDeptTree() {
        //查询部门的数据
        SysDept deptParams = new SysDept();
        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(deptParams);

        //查询所有部门名称不为空的用户
        List<SysDept> userInfoList = userMapper.selectUserInfoDeptIsNotNull();

        sysDepts.addAll(userInfoList);

        List<TreeSelect> treeSelects = buildDeptTreeSelect(sysDepts);
        return treeSelects;
    }

    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
//            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            if (StringUtils.isNotNull(n.getParentId()) && StringUtils.equals(n.getParentId(),t.getDeptId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    /**
     * @param userIdList
     * @return
     */
    @Override
    public List<SysUser> queryUserInfoByUserId(List<String> userIdList) {
        return userMapper.selectUserInfoByIds(userIdList);
    }

    /**
     * <p>
     *     查询市级下面的用户
     * </p>
     * @return
     */
    @Override
    public List<CityUser> queryUserTreeCity() {
        Map<String, List<SysUser>> sysUserMap = null;
        List<SysUser> sysUsers = userMapper.selectUserDeptIsNotNull();
        List<CityUser> list = new ArrayList<>();
        if(sysUsers != null && !sysUsers.isEmpty()){
            sysUserMap = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getCity));
            for(Map.Entry<String, List<SysUser>> v : sysUserMap.entrySet()){
                CityUser cityUser = new CityUser();
                cityUser.setCity(v.getKey());
                cityUser.setChild(v.getValue());
                list.add(cityUser);
            }
        }
        return list;
    }

    /**
     * @param userIds
     */
    @Override
    public List<SysDept> queryDeptName(List<String> deptIds) {



       List<SysDept> r = userMapper.queryDeptName(deptIds);
       return r;
    }

    /**
     * <p>
     * 通过传入的用户ID查询该用户所在部门下的所有用户
     * </p>
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<SysUser> queryUserInDeptAllUser(String userId) {
        SysUser sysUser = userMapper.selectUserById(userId);
        if(sysUser != null){
            //查询出当前用户的部门ID
            String deptId = sysUser.getDeptId();
            List<SysUser> result = userMapper.selectUserByDeptIdList(deptId);
            return result;
        }
        return null;
    }

    /**
     * 通过角色ID查询用户
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryUserByRoleId(String roleId) {
        List<SysUser> r = userMapper.queryUserByRoleId(roleId);
        if(r != null && !r.isEmpty()){
            List<Map<String, Object>> collect = r.stream().map(k -> {
                Map<String, Object> t = new HashMap<>();
                t.put("label", k.getNickName());
                t.put("userId", k.getUserId());
                t.put("isLeaf", true);
                return t;
            }).sorted(Comparator.comparing(k -> {
                String label = (String)k.get("label");
                if(StringUtils.isNotBlank(label)){
                    String firstLetter = PinyinUtil.getFirstLetter(label, "");
                    String sub = StrUtil.sub(firstLetter, 0, 1);
                    return sub;
                }
                return "";
            })).collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }

    /**
     * <p>
     *      注册白名单用户
     * </p>
     *
     * @param sysUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean registerWithUser(RegisterWhiteUserForm params) {
        //前置效验
        //判断确认密码和密码是否一至
        if(!StringUtils.equals(params.getPassword(),params.getConfimPassword())){
            throw new RuntimeException("密码和确认密码输入不一至");
        }

        if (StringUtils.isBlank(params.getUsci())) {
            throw new RuntimeException("用户名不可以为空");
        }

        //插入用户
        SysUser sysUser = new SysUser();
        sysUser.setUserId(IdUtil.simpleUUID());
        sysUser.setNickName(params.getEnterName());
        sysUser.setUserName(params.getUsci());
        sysUser.setPhonenumber(params.getPhone());
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setProvince(params.getProvince());
        sysUser.setCity(params.getCity());
        sysUser.setDistrict(params.getCounty());
//        sysUser.setPassword(SecurityUtils.encryptPassword(params.getPassword()));
        sysUser.setPassword(MD5Utils.encrypt(params.getUsci(),params.getPassword()));
        userMapper.insertUser(sysUser);

        //插入用户与角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
        sysUserRole.setUserId(sysUser.getUserId());
        List<SysUserRole> list = new ArrayList<>();
        list.add(sysUserRole);
        userRoleMapper.batchUserRole(list);

        return true;
    }

    /**
     * 更新用户角色为白名单角色
     *
     * @param sysUser
     * @return
     */
    @Override
    public void updateWhiteUserRole(SysUser sysUser) {
        //查询用户ID通过社会信用代码
        SysUser dbSysUser = userMapper.selectUserByUserName(sysUser.getUserName());
        if(dbSysUser != null){
            String userId = dbSysUser.getUserId();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
            SysUserRole dbUserRole = userRoleMapper.selectBaseIdByUserIdAndRoleId(sysUserRole);
            if(dbUserRole != null){
                sysUserRole.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
                sysUserRole.setNewRoleId("a6d8cffc59db46d6a1b1f9e6de06a0a7");
                userRoleMapper.updateWhiteUserRole(sysUserRole);
            }else{
                sysUserRole.setRoleId("a6d8cffc59db46d6a1b1f9e6de06a0a7");
                userRoleMapper.insertUserWhiteRole(sysUserRole);
            }
        }else{
            throw new RuntimeException("未找到该社会信用码所对应用户");
        }
    }

    /**
     * 插入用户角色
     *
     * @param sysUserRole@return
     */
    @Override
    public void insertRoleUser(SysUserRole sysUserRole) {
        userRoleMapper.insertUserWhiteRole(sysUserRole);
    }

    @Override
    public Map<String, String> queryDeptIdAndDeptNameByUserId(List<String> userIds) {
        //查询用户所在的部门
        List<SysUser> r = userMapper.selectUserDeptByUserId(userIds);
        if(r != null && !r.isEmpty()){
            Map<String, String> userIdToDeptName = r.stream().filter(k -> !(k == null)).collect(Collectors.toMap(SysUser::getUserId, v -> v.getDeptName()));
            return userIdToDeptName;
        }
        return new HashMap<>();
    }
}
